package com.example.week2_try2;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity3 extends AppCompatActivity implements Runnable{

    public static final String TAG= "Exchange";

//    float dollar_rate,euro_rate,won_rate;
    float dollar_rate;
    float euro_rate;
    float won_rate;
    Handler handler;//发送接受都要用，放全局，不能直接方法（可定义，赋值
    TextView screen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        //从SharedPreferences中获取汇率更新时间
        SharedPreferences sp=getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        String date=sp.getString("date","the first time");
        Log.i(TAG, "onCreate: date="+date);

        //获取系统当前时间
        Date now = Calendar.getInstance().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        final String todayStr=sdf.format(now);
        Log.i(TAG, "onCreate: now="+todayStr);

        loadtoSP();
        screen=findViewById(R.id.result);

        //启动线程
//        Thread thread=new Thread(this);//要放当前对象
//        thread.start();//自动调用run方法

        //用其他方法
//        MyTask myTask = new MyTask();
//        myTask.setHandler(handler);
//        Thread thread = new Thread(myTask);
//        thread.start();

        handler=new Handler(Looper.myLooper()){//加入队列对象只是构造对象 有消息来才执行
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.d(TAG, "handleMessage: 收到消息");
                if(msg.what==6){
                    //取数据
                    Bundle bundle=(Bundle) msg.obj;
                    dollar_rate=bundle.getFloat("dollar_rate");
                    euro_rate=bundle.getFloat("euro_rate");
                    won_rate=bundle.getFloat("won_rate");
                    try {
                        Date updated_date=sdf.parse(date);
                        long diff=now.getTime()-updated_date.getTime();
                        long day=diff/(1000*24*60*60);
                        Log.i(TAG, "handleMessage: day="+day);
                        Log.i(TAG, "handleMessage: 当前时间与记录时间：当前时间-"+now+"\t 记录时间-"+updated_date);

                        if(day>0){
                            //更新时间在当前时间与不同日期时再次更新
                            savetoSP(dollar_rate,euro_rate,won_rate,todayStr);
                            Toast.makeText(MainActivity3.this, "汇率已更新", Toast.LENGTH_SHORT).show();
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Log.d(TAG, "handleMessage: dollar_rate="+dollar_rate);
                    Log.d(TAG, "handleMessage: euro_rate="+euro_rate);
                    Log.d(TAG, "handleMessage: won_rate="+won_rate);
                    //screen.setText(str);
                }
                super.handleMessage(msg);
            }
        };


        //用其他方法
        MyTask myTask = new MyTask();
        myTask.setHandler(handler);
        Thread thread = new Thread(myTask);
        thread.start();
        //        dollar_rate=intent.getDoubleExtra("dollar_rate",0.1547d);
//        euro_rate=intent.getDoubleExtra("euro_rate",0.1320d);
//        won_rate=intent.getDoubleExtra("won_rate",501d);
    }

    private void loadtoSP() {
        SharedPreferences sp=getSharedPreferences("myrate", Activity.MODE_PRIVATE);

        PreferenceManager.getDefaultSharedPreferences(this);
        dollar_rate=sp.getFloat("dollar_rate",0.11f);
        euro_rate=sp.getFloat("euro_rate",0.22f);
        won_rate=sp.getFloat("won_rate",0.33f);
    }

    private void savetoSP(float newDollar, float newEuro, float newWon,String now) {
        SharedPreferences sp=getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);

        SharedPreferences.Editor editor= sp.edit();
        editor.putFloat("dollar_rate", newDollar);
        editor.putFloat("euro_rate", newEuro);
        editor.putFloat("wonr_rate", newWon);
        editor.putString("date",now);

        editor.apply();
    }

    public void click(View btn){
        EditText input_num_edit = findViewById(R.id.input_num);
        String input_num = input_num_edit.getText().toString();
        screen=findViewById(R.id.result);
        if(input_num.equals("")){
            Toast.makeText(MainActivity3.this, "Please input number!", Toast.LENGTH_SHORT).show();
            Toast dialog;
            screen.setText(R.string.hello);
        }
        else{

            float money=Float.valueOf(input_num);
            String result_msg="";
            if(btn.getId()==R.id.dollar){
                result_msg=String.valueOf(money*dollar_rate);
            }
            else if(btn.getId()==R.id.euro){
                result_msg=String.valueOf(money*euro_rate);
            }
            else if(btn.getId()==R.id.won){
                result_msg=String.valueOf(money*won_rate);

            }
            screen.setText(result_msg);


        }
    }

    public void open(View btn){
        openConfig();
        //提取方法——右键refactor -》extra method
    }

    private void openConfig() {
        //打开新窗口
        Intent first = new Intent(this, MainActivity4.class);//this当前activity对象
        //Intent first = new Intent(this, RateListActivity.class);//this当前activity对象

        //putExtra--传递参数
        first.putExtra("dollar_rate", dollar_rate);
        first.putExtra("euro_rate", euro_rate);
        first.putExtra("won_rate", won_rate);
        Log.i(TAG, "Open:dollar_rate=======" + dollar_rate);
        Log.i(TAG, "Open:euro_rate=" + euro_rate);
        Log.i(TAG, "Open:won_rate=" + won_rate);

        //startActivity(first);
        startActivityForResult(first, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1&&resultCode==2){
            dollar_rate=data.getFloatExtra("dollar_rate",0.1547f);
            euro_rate=data.getFloatExtra("euro_rate",0.1320f);
            won_rate=data.getFloatExtra("won_rate",501f);
//            SharedPreferences sp=getSharedPreferences("myrate", Activity.MODE_PRIVATE);
//
//            PreferenceManager.getDefaultSharedPreferences(this);
//            dollar_rate=sp.getFloat("dollar_rate",0.0f);
//            euro_rate=sp.getFloat("euro_rate",0.0f);
//            won_rate=sp.getFloat("won_rate",0.0f);


            Log.i(TAG,"onActivityResult:dollar_rate="+dollar_rate);
            Log.i(TAG,"onActivityResult:euro_rate="+euro_rate);
            Log.i(TAG,"onActivityResult:won_rate="+won_rate);

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.setting){
            //打开新窗口
            openConfig();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void run() {
        Log.d(TAG, "run: ================================");
        //延迟
//        try{
//            Thread.sleep(3000);
//        }catch (InterruptedException e){
//            e.printStackTrace();
//        }
        //获取网络数据
//        URL url=null;
//        try{
//            url=new URL("https://www.usd-cny.com/bankofchina.htm");
//            HttpURLConnection http=(HttpURLConnection) url.openConnection();
//            InputStream in = http.getInputStream();
//            String html= inputStream2String(in);
//            Log.d(TAG, "run: html="+html);
//        }catch (MalformedURLException e){
//            e.printStackTrace();
//        }catch (IOException e){
//            e.printStackTrace();
//
//        }
        Bundle bundle=new Bundle();
        try {
            Document doc = null;
            doc = Jsoup.connect("https://usd-cny.com/").get();
            Log.i(TAG, "run: "+doc.title());
            Elements tables=doc.getElementsByTag("table");
            Element firstTable=tables.first();//单位元素
            //通过行获取数据
            Elements trs=firstTable.getElementsByTag("tr");
            trs.remove(0);
            for(Element tr:trs){
                Log.i(TAG, "run: tr="+tr);
                //从行中获得td元素
                Elements tds=tr.getElementsByTag("td");
                //获取第一列
                Element td1=tds.get(0);
                Element td2=tds.get(4);
                Log.i(TAG, "run: td1="+td1.text()+"\n run: td2="+td2.text());
                //加过滤项
                if(td1.text().equals("美元")){
                    float dollar_rate = 100f/Float.parseFloat(td2.text());
                    bundle.putFloat("dollar_rate",dollar_rate);
                }
                else if(td1.text().equals("欧元")){
                    float euro_rate = 100f/Float.parseFloat(td2.text());
                    bundle.putFloat("euro_rate",euro_rate);
                }
                else if(td1.text().equals("韩币")){
                    float won_rate = 100f/Float.parseFloat(td2.text());
                    bundle.putFloat("won_rate",won_rate);
                }
            }
            Message msg=handler.obtainMessage();//括号内可写what
            msg.what=6;
            msg.obj=bundle;
            handler.sendMessage(msg);
            //            for(Element item:firstTable.getElementsByClass("bz")){
//                Log.i(TAG, "run: item="+item.text());
//            }
            //Log.d(TAG, "run: 消息内容");

            //Log.i(TAG, "run: table="+firstTable);
//            List<String> rate = new List<String>;
//            Elements tds= firstTable.getElementsByTag("td");
//            for(int i=0;i<tds.size();i+=5){
//                Element td1=tds.get(i);
//                Element td2=tds.get(i+1);
//                //if(td1.text().equals("美元")||td1.text().equals("欧元")||td1.text().equals("韩币"))
//                Log.i(TAG, "run: td1="+td1.text()+"\n run: td2="+td2.text());
////                Log.i(TAG, "run: td2="+td2.text());
//
//            }
//获取表格内元素
//            Elements ths=firstTable.getElementsByTag("th");
//            for(Element th: ths){
//                Log.i(TAG, "run: th="+th);
//                Log.i(TAG, "run: th.html="+th.html());//包含标签的内容
//
//                //获取th内容
//                th.text();//获取去除标签的文本
//            }
//            Element th2=ths.get(1);
//            Log.i(TAG, "run: th2="+th2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //发送消息
//        Message msg=handler.obtainMessage();//括号内可写what
//        msg.what=6;
//         msg.obj="Hello from run";
//        handler.sendMessage(msg);
//        Log.d(TAG, "run: 消息内容");
        //                if(td1.text().equals("美元")||td1.text().equals("欧元")||td1.text().equals("韩币")){
//                    Map rate_tmp=new HashMap();
//                    rate_tmp.put(td1.text(),td2.text());
//                    rate.add(rate_tmp);
//                }

//                Log.i(TAG, "run: tds.count="+tds.size());//若为0则舍去，过滤title
    }

    private String inputStream2String(InputStream inputStream) throws IOException{
        final int bufferSize=1024;
        final char[] buffer=new char[bufferSize];
        final StringBuilder out=new StringBuilder();
        Reader in = new InputStreamReader(inputStream,"gb2312");
        while(true){
            int rsz=in.read(buffer,0,buffer.length);
            if(rsz<0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }
}